const express = require('express');
const router = express.Router();
const { pool } = require('../db');
const authMiddleware = require('../middlewares/authMiddleware');

// 应用认证中间件到所有订单相关路由
router.use(authMiddleware);

// 生成订单号
function generateOrderNo() {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 1000);
  return `ORD${timestamp}${random}`;
}

// 创建订单
router.post('/orders', async (req, res) => {
  try {
    const { customer_name, customer_phone, total_amount, items } = req.body;
    
    if (!customer_name || !total_amount || !items || !Array.isArray(items)) {
      return res.status(400).json({ error: '缺少必要参数或参数格式错误' });
    }
    
    const order_no = generateOrderNo();
    
    const [result] = await pool.query(
      'INSERT INTO orders (order_no, customer_name, customer_phone, total_amount, items) VALUES (?, ?, ?, ?, ?)',
      [order_no, customer_name, customer_phone || '', total_amount, JSON.stringify(items)]
    );
    
    res.status(201).json({
      id: result.insertId,
      order_no,
      customer_name,
      customer_phone,
      total_amount,
      items,
      order_time: new Date(),
      print_status: 0
    });
  } catch (error) {
    console.error('创建订单失败:', error);
    res.status(500).json({ error: '创建订单失败' });
  }
});

// 获取订单列表
router.get('/orders', async (req, res) => {
  try {
    const { page = 1, limit = 10, print_status, keyword } = req.query;
    const offset = (page - 1) * limit;
    
    let query = 'SELECT * FROM orders';
    let params = [];
    let whereClause = false;
    
    // 处理状态筛选
    if (print_status !== undefined) {
      query += ' WHERE print_status = ?';
      params.push(print_status);
      whereClause = true;
    }
    
    // 处理关键词搜索
    if (keyword) {
      const keywordOperator = whereClause ? ' AND' : ' WHERE';
      query += `${keywordOperator} (order_no LIKE ? OR customer_name LIKE ?)`;
      const searchParam = `%${keyword}%`;
      params.push(searchParam, searchParam);
    }
    
    query += ' ORDER BY order_time DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), offset);
    
    const [orders] = await pool.query(query, params);
    
    // 获取总数量
    let countQuery = 'SELECT COUNT(*) as total FROM orders';
    let countParams = [];
    let countWhereClause = false;
    
    // 处理状态筛选的总数量查询
    if (print_status !== undefined) {
      countQuery += ' WHERE print_status = ?';
      countParams.push(print_status);
      countWhereClause = true;
    }
    
    // 处理关键词搜索的总数量查询
    if (keyword) {
      const keywordOperator = countWhereClause ? ' AND' : ' WHERE';
      countQuery += `${keywordOperator} (order_no LIKE ? OR customer_name LIKE ?)`;
      const searchParam = `%${keyword}%`;
      countParams.push(searchParam, searchParam);
    }
    
    const [countResult] = await pool.query(countQuery, countParams);
    
    res.json({
      orders: orders.map(order => ({
        ...order,
        items: typeof order.items === 'string' ? JSON.parse(order.items) : order.items
      })),
      total: countResult[0].total,
      page: parseInt(page),
      limit: parseInt(limit),
      pages: Math.ceil(countResult[0].total / limit)
    });
  } catch (error) {
    console.error('获取订单列表失败:', error);
    res.status(500).json({ error: '获取订单列表失败' });
  }
});

// 获取订单详情
router.get('/orders/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const [orders] = await pool.query('SELECT * FROM orders WHERE id = ?', [id]);
    
    if (orders.length === 0) {
      return res.status(404).json({ error: '订单不存在' });
    }
    
    const order = orders[0];
    res.json({
      ...order,
      items: typeof order.items === 'string' ? JSON.parse(order.items) : order.items
    });
  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.status(500).json({ error: '获取订单详情失败' });
  }
});

// 标记订单为已打印
router.put('/orders/:id/print', async (req, res) => {
  try {
    const { id } = req.params;
    const { printer_info } = req.body;
    
    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 更新订单状态
      await connection.query(
        'UPDATE orders SET print_status = 1 WHERE id = ?',
        [id]
      );
      
      // 记录打印日志
      // 插入打印记录时不记录printer_info
      await connection.query(
        'INSERT INTO print_records (order_id) VALUES (?)',
        [id]
      );
      
      await connection.commit();
      res.json({ success: true, message: '订单打印成功' });
    } catch (transactionError) {
      await connection.rollback();
      throw transactionError;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('打印订单失败:', error);
    res.status(500).json({ error: '打印订单失败' });
  }
});

// 更新订单
router.put('/orders/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { customer_name, customer_phone, total_amount, items } = req.body;
    
    if (!customer_name || !total_amount || !items || !Array.isArray(items)) {
      return res.status(400).json({ error: '缺少必要参数或参数格式错误' });
    }
    
    const [result] = await pool.query(
      'UPDATE orders SET customer_name = ?, customer_phone = ?, total_amount = ?, items = ? WHERE id = ?',
      [customer_name, customer_phone || '', total_amount, JSON.stringify(items), id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ error: '订单不存在' });
    }
    
    // 返回更新后的订单信息
    const [updatedOrders] = await pool.query('SELECT * FROM orders WHERE id = ?', [id]);
    const order = updatedOrders[0];
    
    res.json({
      ...order,
      items: typeof order.items === 'string' ? JSON.parse(order.items) : order.items,
      message: '订单更新成功'
    });
  } catch (error) {
    console.error('更新订单失败:', error);
    res.status(500).json({ error: '更新订单失败' });
  }
});

// 删除订单
router.delete('/orders/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const [result] = await pool.query('DELETE FROM orders WHERE id = ?', [id]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ error: '订单不存在' });
    }
    
    res.json({ success: true, message: '订单删除成功' });
  } catch (error) {
    console.error('删除订单失败:', error);
    res.status(500).json({ error: '删除订单失败' });
  }
});

// 获取打印记录
router.get('/print-records', async (req, res) => {
  try {
    const { page = 1, limit = 10, keyword = '' } = req.query;
    const offset = (page - 1) * limit;
    
    let query = `SELECT pr.id, pr.order_id, pr.print_time, o.order_no, o.customer_name 
                FROM print_records pr
                LEFT JOIN orders o ON pr.order_id = o.id`;
    let params = [];
    let countQuery = 'SELECT COUNT(*) as total FROM print_records pr LEFT JOIN orders o ON pr.order_id = o.id';
    let countParams = [];
    
    if (keyword) {
      query += ' WHERE (o.order_no LIKE ? OR o.customer_name LIKE ?)';
      countQuery += ' WHERE (o.order_no LIKE ? OR o.customer_name LIKE ?)';
      const searchParam = `%${keyword}%`;
      params.push(searchParam, searchParam);
      countParams.push(searchParam, searchParam);
    }
    
    query += ' ORDER BY pr.print_time DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), offset);
    
    const [records] = await pool.query(query, params);
    const [countResult] = await pool.query(countQuery, countParams);
    
    res.json({
      records,
      total: countResult[0].total,
      page: parseInt(page),
      limit: parseInt(limit),
      pages: Math.ceil(countResult[0].total / limit)
    });
  } catch (error) {
    console.error('获取打印记录失败:', error);
    res.status(500).json({ error: '获取打印记录失败' });
  }
});

module.exports = router;